#pragma once

#include <vector>

namespace solution_054
{

class Solution
{
public:
    std::vector<int> spiralOrder(std::vector< std::vector<int> >& matrix)
    {
        const int rows = matrix.size();
        const int cols = matrix.front().size();

        std::vector<int> spiral;
        for (int diag = 0; diag < (std::min(rows, cols) + 1) / 2; ++diag) {
            for (int row = diag,
                     col = diag;
                     col <= cols - diag - 1; ++col)
                spiral.push_back(matrix.at(row).at(col));

            for (int row = diag + 1,
                     col = cols - diag - 1;
                     row < rows - diag - 1 && col >= diag; ++row)
                spiral.push_back(matrix.at(row).at(col));

            for (int row = rows - diag - 1,
                     col = cols - diag - 1;
                     row > diag && col >= diag; --col)
                spiral.push_back(matrix.at(row).at(col));

            for (int row = rows - diag - 2,
                     col = diag;
                     row > diag && col < cols - diag - 1; --row)
                spiral.push_back(matrix.at(row).at(col));
        }
        return spiral;
    }
};

}  /* namespace solution_048 */
